/**
 * @(#)SimulatorApkdownloadServiceImpl.java 2017年2月28日
 * Copyright(C) 2015 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.service.impl;

import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.dao.ISimulatorApkDownloadConfigDAO;
import org.jsbd.boss.domian.SimulatorApkDownloadConfig;
import org.jsbd.boss.domian.SimulatorType;
import org.jsbd.boss.service.ISimulatorApkdownloadService;
import org.jsbd.boss.util.PhoneUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhexinit.proxy.domain.HttpContext;
import com.zhexinit.proxy.domain.HttpProxyLog;
import com.zhexinit.proxy.domain.ProxyHost;
import com.zhexinit.proxy.util.ProxyHostUtils;

import edu.hziee.common.queue.DelayExecuteBuffer;

/**
 * TODO 请加入本类的说明
 * 
 * @author <a href="mailto:zhangbinghua@zhexinit.com" >zbh</a>
 * @version 1.0.0
 */
@Service
public class SimulatorApkdownloadServiceImpl implements ISimulatorApkdownloadService {
	public static final Logger LOGGER = LoggerFactory.getLogger(SimulatorApkdownloadServiceImpl.class);

	
	@Autowired
	private RedisClient redisClient;
	
	private static final int ONE_DAY = 60 * 60 * 24;
	@Autowired
	private DelayExecuteBuffer<HttpProxyLog> zxHttpProxyLogBuffer;
	@Autowired
	private ISimulatorApkDownloadConfigDAO simulatorApkDownloadConfigDAO;

	@Override
	public void simulatordownloadApk() throws Exception {
		List<SimulatorApkDownloadConfig> list = simulatorApkDownloadConfigDAO.getSimulatorApkDownloadConfigList();
		if (list != null && list.size() > 0) {
			for (SimulatorApkDownloadConfig config : list) {
				if(checkdownloadCount(config)){
					LOGGER.debug("{} 已经执行超过最大次数:{}",config.getUrl(),config.getCount());
					continue;
				}
				String type = config.getType();
				switch (type) {
				case SimulatorType.url:
					downloadByurl(config);
					break;
				case SimulatorType.migu:
					downloadMigu(config);
					break;
				case SimulatorType.baiduhelp:
					downloadbaiduhelp(config);
					break;
				default:
					throw new Exception("not found type:" + type);
				}
			}
		}
	}

	@Override
	public void saveSimulatorApkDownloadConfig(SimulatorApkDownloadConfig config) {
		simulatorApkDownloadConfigDAO.saveSimulatorApkDownloadConfig(config);
	}

	@Override
	public void abondeSimulatorApkDownloadConfig(String id) {
		simulatorApkDownloadConfigDAO.abandonSimulatorApkDownloadConfig(id);
	}

	@Override
	public void effectSimulatorApkDownloadConfig(String id) {
		simulatorApkDownloadConfigDAO.effectSimulatorApkDownloadConfig(id);

	}

	@Override
	public void updateSimulatorApkDownloadConfig(SimulatorApkDownloadConfig config) {
		simulatorApkDownloadConfigDAO.updateSimulatorApkDownloadConfig(config);

	}

	@Override
	public Map<String, Object> getApkConfigByPage(SimulatorApkDownloadConfig config) {
		return simulatorApkDownloadConfigDAO.selectConfigPageListMap(config);

	}
	
	public void downloadByurl(SimulatorApkDownloadConfig config) {
		String miguapkdownloadcountkey = getSuccessKey(config);
		String downloadurl = config.getUrl();
		download(downloadurl, "channeldownloadbyurl");
		redisClient.incrementBy(miguapkdownloadcountkey, 1, ONE_DAY);
	}
	public void downloadMigu(SimulatorApkDownloadConfig config){
		String miguapkdownloadcountkey = getSuccessKey(config);
		String downloadurl = "http://extension.miguxue.com/interface/downloadConfirm.action?channel=" + config.getUrl()	+ "&clientId=1063114460";
		download(downloadurl, "channeldownloadMigu");
		redisClient.incrementBy(miguapkdownloadcountkey, 1, ONE_DAY);
	}
	public void downloadbaiduhelp(SimulatorApkDownloadConfig config){
		String miguapkdownloadcountkey = getSuccessKey(config);
		String downloadurl = config.getUrl();
		download(downloadurl, "channeldownloadbaiduhelp");
		redisClient.incrementBy(miguapkdownloadcountkey, 1, ONE_DAY);
	}

	/**
	 * 
	 * checkdownloadCount:TODO 请描述该方法是做什么用途的
	 * @author <a href="mailto:zhangbinghua@zhexinit.com" >zbh</a>
	 * @param config
	 * @return
	 */
	private boolean checkdownloadCount(SimulatorApkDownloadConfig config) {
		String miguapkdownloadcountkey = getSuccessKey(config);
		Long counter = redisClient.getLong(miguapkdownloadcountkey);
		if (counter == null) {
			counter = 0L;
		}
		return counter > config.getCount();

	}
	
	public String getSuccessKey(SimulatorApkDownloadConfig config){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		String date = df.format(cal.getTime());
		String param = config.getUrl();
		String miguapkdownloadcountkey = "MIGUAPKDOWNLOAD_TODAYSUCC_COUNT_" + param + "_" + date;
		return miguapkdownloadcountkey;
	}
	
	
	public  void download(String downloadurl,String type){
		
		String release = PhoneUtil.getRelease();
		String hstype = PhoneUtil.getHstype();
		String build = PhoneUtil.getBuild();

		HttpContext httpContext = new HttpContext();
		httpContext.setOrderId(UUID.randomUUID().toString());
		httpContext.setProvinceId("-1");
		httpContext.setImsi(httpContext.getOrderId());
		httpContext.setBizType(type);
		httpContext.setStep(0);
		HttpProxyLog httpProxyLog = new HttpProxyLog();
		httpProxyLog.setHttpContext(httpContext);
		httpProxyLog.setUrl(downloadurl);
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("Accept",		"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		headerMap.put("Accept-Encoding", "gzip,deflate");
		headerMap.put("Accept-Language", "zh-CN,en-US;q=0.8");
		headerMap.put("Accept-Charset", "utf-8, iso-8859-1, utf-16, gb2312, gbk, *;q=0.7");
		headerMap.put("User-Agent", "Mozilla/5.0 (Linux; U; Android " + release + "; zh-cn; "+ hstype + " Build/" + build	+ ") AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");

		httpProxyLog.setHeaderMap(headerMap);

		httpDownload(httpProxyLog, zxHttpProxyLogBuffer, false);
	}
	
	

	public static boolean httpDownload(HttpProxyLog httpProxyLog, DelayExecuteBuffer<HttpProxyLog> httpProxyLogBuffer,
			boolean https) {
		HttpContext httpContext = httpProxyLog.getHttpContext();
		String provinceId = httpContext.getProvinceId();
		String imsi = httpContext.getImsi();
		ProxyHost proxyHost = ProxyHostUtils.getProxyHost(imsi, provinceId, 5, httpProxyLog.getHttpContext().getBizType());
		httpProxyLog.setIpConnect(proxyHost.getIp());
		httpProxyLog.getHeaderMap().put("Ip", proxyHost.getIp());

		long t = System.currentTimeMillis();

		String url = httpProxyLog.getUrl();
		try {
			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost.getAddress(), proxyHost.getPort()));
			URLConnection conn = new URL(url).openConnection(proxy);

			String release = PhoneUtil.getRelease();
			String hstype = PhoneUtil.getHstype();
			String build = PhoneUtil.getBuild();

			conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
			conn.setRequestProperty("Accept-Language", "zh-CN,en-US;q=0.8");
			conn.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, gb2312, gbk, *;q=0.7");
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; U; Android " + release + "; zh-cn; " + hstype+ " Build/" + build + ") AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
			InputStream in = conn.getInputStream();
			//ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int len = 0;
			if ((len = in.read(b)) > -1) {
				// out.write(b, 0, len);
				LOGGER.info("download success");
			}
			 //FileUtil.writeBytes("d:/"+UUID.randomUUID()+".apk", out.toByteArray());
			// httpGet.releaseConnection();
			in.close();
			// out.close();

		} catch (Exception e) {
			LOGGER.error("http 代理请求失败 [{}]", httpProxyLog, e);
			return false;
		} finally {
			long t1 = System.currentTimeMillis();
			httpProxyLog.setReadTime(t1 - t);
			httpProxyLogBuffer.add(httpProxyLog);
		}
		return true;
	}

}
